<template>
  <div id="homePage">
    <!-- 搜索框 -->
    <div class="search-bar">
      <a-input-search
        v-model:value="searchParams.searchText"
        placeholder="从海量图片中搜索"
        enter-button="搜索"
        size="large"
        @search="doSearch"
      />
    </div>
    <!-- 分类和标签筛选 -->
    <a-tabs v-model:active-key="selectedCategory" @change="doSearch">
      <a-tab-pane key="all" tab="全部" />
      <a-tab-pane v-for="category in categoryList" :tab="category" :key="category"
                  @click="doRecordCategory(category)" />
    </a-tabs>
    <div class="tag-bar">
      <span style="margin-right: 8px">标签：</span>
      <a-space :size="[0, 8]" wrap>
        <a-checkable-tag
          v-for="(tag, index) in tagList"
          :key="tag"
          v-model:checked="selectedTagList[index]"
          @change="handleTags(tag)"
        >
          {{ tag }}
        </a-checkable-tag>
      </a-space>
    </div>
    <!-- 图片列表 -->
    <PictureList :dataList="dataList" :loading="loading" :userId="currentUserId" @like-changed="handleLikeChanged" />
    <!-- 分页 -->
    <a-pagination
      style="text-align: right"
      v-model:current="searchParams.current"
      v-model:pageSize="searchParams.pageSize"
      :total="total"
      @change="onPageChange"
    />
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue'
import {
  listPictureTagCategoryUsingGet,
  listPictureVoByPageUsingPost
} from '@/api/pictureController.ts'
import { message } from 'ant-design-vue'
import PictureList from '@/components/PictureList.vue'
import { getTagsUsingGet, recordTagsUsingPost } from '@/api/tagsController.ts'
import { getCategoriesUsingGet, recordCategoriesUsingPost } from '@/api/categoriesController.ts'
import { useLoginUserStore } from '@/stores/useLoginUserStore.ts'
import PictureListTest from '@/components/PictureListTest.vue'
// 定义数据
const dataList = ref<API.PictureVO[]>([])
const total = ref(0)
const loading = ref(true)
const userStore = useLoginUserStore()
const currentUserId = computed(() => userStore.loginUser?.id)

// 修改点赞处理函数
const handleLikeChanged = (pictureId: number, newLikeCount: number) => {
  const target = dataList.value.find(p => p.id === pictureId)
  if (target) {
    target.likeCount = newLikeCount
    target.isLiked = !target.isLiked  // 需要确保接口返回isLiked字段
  }
}

// 搜索条件
const searchParams = reactive<API.PictureQueryRequest>({
  current: 1,
  pageSize: 12,
  sortField: 'createTime',
  sortOrder: 'descend'
})

// 获取数据
const fetchData = async () => {
  loading.value = true
  // 转换搜索参数
  const params = {
    ...searchParams,
    fields: ['id', 'name', 'url', 'viewCount', 'likeCount'],
    tags: [] as string[]
  }
  if (selectedCategory.value !== 'all') {
    params.category = selectedCategory.value
  }
  // [true, false, false] => ['java']
  selectedTagList.value.forEach((useTag, index) => {
    if (useTag) {
      params.tags.push(tagList.value[index])
    }
  })
  const res = await listPictureVoByPageUsingPost(params)
  if (res.data.code === 0 && res.data.data) {
    dataList.value = res.data.data.records ?? []
    total.value = res.data.data.total ?? 0
  } else {
    message.error('获取数据失败，' + res.data.message)
  }
  loading.value = false
}

// 页面加载时获取数据，请求一次
onMounted(() => {
  fetchData()
})

// 分页参数
const onPageChange = (page: number, pageSize: number) => {
  searchParams.current = page
  searchParams.pageSize = pageSize
  fetchData()
}

// 搜索
const doSearch = () => {
  // 重置搜索条件
  searchParams.current = 1
  fetchData()
}

/**
 * 处理标签
 * @param tag
 */
const handleTags = (tag: string) => {
  doSearch()
  doRecordTag(tag)
}

// 搜索
const doRecordTag = async (tag: any) => {
  console.log(tag)
  const params = {
    tagName: tag
  }
  const res = await recordTagsUsingPost(params)
  if (res.data.code === 0 && res.data.data) {
    console.log('recordTagsUsingPost success')
  } else {
    message.error('获取数据失败，' + res.data.message)
  }
}

/**
 * 处理分类
 */
const handleCategories = (category: string) => {
  doSearch()
  doRecordCategory(category)
}

const doRecordCategory = async (category: any) => {
  console.log(category)
  const params = {
    categoryName: category
  }
  const res = await recordCategoriesUsingPost(params)
  if (res.data.code === 0 && res.data.data) {
    console.log('recordCategoriesUsingPost success')
  } else {
    message.error('获取数据失败，' + res.data.message)
  }
}

// 标签和分类列表
const categoryList = ref<string[]>([])
const selectedCategory = ref<string>('all')
const tagList = ref<string[]>([])
const selectedTagList = ref<boolean[]>([])

/**
 * 获取标签和分类选项
 * @param values
 */
const getTagCategoryOptions = async () => {
  const res = await listPictureTagCategoryUsingGet()
  if (res.data.code === 0 && res.data.data) {
    tagList.value = res.data.data.tagList ?? []
    categoryList.value = res.data.data.categoryList ?? []
  } else {
    message.error('获取标签分类列表失败，' + res.data.message)
  }
}



// /**
//  * 获取标签选项
//  * @param values
//  */
// const getTagOptions = async () => {
//   const res = await getTagsUsingGet()
//   if (res.data.code === 0 && res.data.data) {
//     console.log("标签选项："+res.data.data)
//     tagList.value = res.data.data.map(tag => tag.tagName);
//     console.log("标签选项："+tagList.value)
//   } else {
//     message.error('获取标签分类列表失败，' + res.data.message)
//   }
// }
//
// /**
//  * 获取标签选项
//  * @param values
//  */
// const getCategoryOptions = async () => {
//   const res = await getCategoriesUsingGet()
//   if (res.data.code === 0 && res.data.data) {
//     console.log("标签选项："+res.data.data)
//     categoryList.value = res.data.data.map(category => category.categoryName);
//     console.log("标签选项："+categoryList.value)
//   } else {
//     message.error('获取标签分类列表失败，' + res.data.message)
//   }
// }

onMounted(() => {
  getTagCategoryOptions()
})
</script>

<style scoped>
#homePage {
  margin-bottom: 16px;
}

#homePage .search-bar {
  max-width: 480px;
  margin: 0 auto 16px;
}

#homePage .tag-bar {
  margin-bottom: 16px;
}
</style>
